package com.sgb.member.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;

import com.sgb.member.MemberConfig;
import com.sgb.member.R;
import com.sgb.member.weight.SimpleResult;
import com.sgb.member.weight.UploadFileBean;
import com.swgk.core.util.FileUtil;
import com.swgk.core.util.LogUtil;
import com.swgk.core.util.MToast;
import com.yalantis.ucrop.util.FileUtils;

import java.io.File;

public class ChooseFileUtil {

    // https://www.cnblogs.com/yongdaimi/p/12737413.html
    public static void startFileIntent(Activity activity) {
        // 上传附件
        String[] mimeTypes = {MMimeType.DOC,
                MMimeType.DOCX, MMimeType.PDF, MMimeType.PPT,
                MMimeType.PPTX, MMimeType.XLS, MMimeType.XLSX,
                MMimeType.ZIP, MMimeType.RAR, MMimeType.PNG, MMimeType.JPG, MMimeType.BIN, MMimeType.TXT};

        String[] mimeTypess = {MMimeType.ALL};

        Intent fileIntent = new Intent(Intent.ACTION_GET_CONTENT);
        fileIntent.addCategory(Intent.CATEGORY_OPENABLE);
        //设置类型
        //fileIntent.setType("application/zip|image/png|application/pdf|application/rar|image/jpeg|application/msword|application/vnd.openxmlformats-officedocument.wordprocessingml.document|application/octet-stream|text/plain");
        fileIntent.setType("*/*");

        //在API>=19之后设置多个类型采用以下方式，setType不再支持多个类型
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            fileIntent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypess);
        }
        activity.startActivityForResult(fileIntent, MemberConfig.REQ_FILE_CHOOSE);
    }

    public static UploadFileBean handleFileChoose(Context context, Intent data, SimpleResult<UploadFileBean> simpleResult, int limitSize) {
        Uri uri = data.getData();
        if (uri == null) {
            return null;
        }
        String filePath;
        String fileName;
        String fileType;
        String fileSize;
        int imgRes;
        // 得到uri对路径
        if ("content".equalsIgnoreCase(uri.getScheme()) || "file".equalsIgnoreCase(uri.getScheme())) {
            filePath = FileUtil.getFilePathForN(context, uri);
            fileName = new File(filePath).getName();
            String extension = FileUtil.getExtensionName(fileName);
            if (TextUtils.isEmpty(extension)) {
                MToast.showToast(context, "未获取到文件格式");
                return null;
            }
            if (!extension.equals("pptx") && !extension.equals("ppt") && !extension.equals("pdf")
                    && !extension.equals("png") && !extension.equals("jpg") && !extension.equals("jpeg")
                    && !extension.equals("xls") && !extension.equals("xlsx") && !extension.equals("doc")
                    && !extension.equals("docx") && !extension.equals("zip") && !extension.equals("rar")
                    && !extension.equals("txt")) {
                MToast.showToast(context, "上传附件格式不正确！");
                return null;
            }
            if (checkFileSize(context, filePath, limitSize)) {
                long fileLength = FileUtil.getFileLength(filePath);
                fileSize = FileUtil.formatFileSize(fileLength);
                fileType = FileUtil.getMimeType(new File(filePath));
                switch (fileType) {
                    case "image/jpg":
                    case "image/png":
                    case "image/jpeg":
                        imgRes = R.mipmap.member_icon_file_img;
                        break;
                    case "application/msword":
                    case "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
                        imgRes = R.mipmap.member_icon_file_doc;
                        break;
                    case "application/vnd.ms-powerpoint":
                    case "application/vnd.openxmlformats-officedocument.presentationml.presentation":
                        imgRes = R.mipmap.member_icon_file_ppt;
                        break;
                    case "application/vnd.ms-excel":
                    case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
                        imgRes = R.mipmap.member_icon_file_xlsx;
                        break;
                    case "application/pdf":
                        imgRes = R.mipmap.member_icon_file_pdf;
                        break;
                    default:
                        imgRes = R.mipmap.member_icon_file_doc;
                        break;
                }
                return createUploadFile(filePath, fileName, fileType, imgRes, extension, simpleResult);
            }
            return null;
        }
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
            filePath = FileUtils.getPath(context, uri);
        } else {//4.4以下下系统调用方法
            filePath = FileUtil.getRealPathFromURI(uri, context);
        }
        if (TextUtils.isEmpty(filePath)) {
            MToast.showToast(context, "未找到文件路径");
            return null;
        }
        fileName = new File(filePath).getName();
        String extension = FileUtil.getExtensionName(fileName);
        if (TextUtils.isEmpty(extension)) {
            MToast.showToast(context, "未获取到文件格式");
            return null;
        }
        if (!extension.equals("pptx") && !extension.equals("ppt") && !extension.equals("pdf")
                && !extension.equals("png") && !extension.equals("jpg") && !extension.equals("jpeg")
                && !extension.equals("xls") && !extension.equals("xlsx") && !extension.equals("doc")
                && !extension.equals("docx") && !extension.equals("zip") && !extension.equals("rar")
                && !extension.equals("txt")) {
            MToast.showToast(context, "上传附件格式不正确！");
            return null;
        }

        if (checkFileSize(context, filePath, limitSize)) {
            long fileLength = FileUtil.getFileLength(filePath);
            fileSize = FileUtil.formatFileSize(fileLength);
            fileType = FileUtil.getMimeType(new File(filePath));
            switch (fileType) {
                case "image/jpg":
                case "image/png":
                case "image/jpeg":
                    imgRes = R.mipmap.member_icon_file_img;
                    break;
                case "application/msword":
                case "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
                    imgRes = R.mipmap.member_icon_file_doc;
                    break;
                case "application/vnd.ms-powerpoint":
                case "application/vnd.openxmlformats-officedocument.presentationml.presentation":
                    imgRes = R.mipmap.member_icon_file_ppt;
                    break;
                case "application/vnd.ms-excel":
                case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
                    imgRes = R.mipmap.member_icon_file_xlsx;
                    break;
                case "application/pdf":
                    imgRes = R.mipmap.member_icon_file_pdf;
                    break;
                default:
                    imgRes = R.mipmap.member_icon_file_doc;
                    break;
            }
            return createUploadFile(filePath, fileName, fileType, imgRes, extension, simpleResult);
        }
        LogUtil.d("TAG", "handleFileChoose filePath:" + filePath);
        return null;
    }

    public static UploadFileBean handleFileChoose(Context context, Intent data, SimpleResult<UploadFileBean> simpleResult) {
        return handleFileChoose(context, data, simpleResult,  50);
    }

    private static UploadFileBean createUploadFile(String filePath, String fileName,
                                  String fileType, int imgRes, String extension, SimpleResult<UploadFileBean> simpleResult) {
        UploadFileBean uploadFileBean = new UploadFileBean();
        uploadFileBean.setFileName(fileName);
        uploadFileBean.setFilePath(filePath);
        uploadFileBean.setFileType(fileType);
        uploadFileBean.setImgRes(imgRes);
        uploadFileBean.setExtension(extension);
        simpleResult.onResult(uploadFileBean);
        return uploadFileBean;
    }

    /**
     * 检查文件大小
     *
     * @param filePath 文件路径
     * @return 文件大小
     */
    private static boolean checkFileSize(Context context, String filePath, int limitSize) {
        float sizeCount = 0f;
        long fileLength = FileUtil.getFileLength(filePath);
        String fileSize = FileUtil.formatFileSize(fileLength, FileUtil.SizeUnit.MB);
        if (fileSize.contains("MB")) {
            String fileSizeCount = fileSize.replace("MB", "");
            if (!TextUtils.isEmpty(fileSizeCount)) {
                sizeCount = Float.parseFloat(fileSizeCount);
                if (sizeCount > limitSize) {
                    MToast.showToast(context, "上传文件大小不能超过" + limitSize + "MB!");
                    return false;
                }
            }
        }
        return true;
    }

}
